<template>
  <div class="inventory-count-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>盘点订单</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="盘点单号">
            <el-input
              v-model="searchForm.countCode"
              placeholder="请输入盘点单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="盘点结果">
            <el-select
              v-model="searchForm.countStatus"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="有盈亏" value="有盈亏" />
              <el-option label="无盈亏" value="无盈亏" />
              <el-option label="草稿" value="草稿" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="请选择开始时间"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="请选择结束时间"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="盘点类型">
            <el-select
              v-model="searchForm.countType"
              placeholder="请选择类型"
              clearable
              style="width: 200px"
              :loading="typeLoading"
            >
              <el-option label="全部" value="" />
              <el-option label="存货盘点" value="存货盘点" />
              <el-option label="期初盘点" value="期初盘点" />
              <el-option label="期末盘点" value="期末盘点" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select
              v-model="searchForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              filterable
              style="width: 200px"
              :loading="warehouseLoading"
            >
              <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.warehouseId"
                :label="warehouse.warehouseName"
                :value="warehouse.warehouseId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span>盘点订单列表</span>
            <div class="table-actions">
              <el-button type="success" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增盘点
              </el-button>
              <el-button type="primary" @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          
          <el-table-column prop="countCode" label="盘点单号" width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link type="primary" @click="handleViewDetail(row)">
                {{ row.countCode }}
              </el-link>
            </template>
          </el-table-column>
          
          <el-table-column prop="countStatus" label="盘点结果" width="100">
            <template #default="{ row }">
              <el-tag :type="getResultType(row.countStatus)">
                {{ row.countStatus }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="warehouseId" label="仓库ID" width="100" />
          <el-table-column prop="warehouseName" label="仓库名称" width="120" show-overflow-tooltip />
          
          <el-table-column prop="countType" label="盘点类型" width="120" />
          
          <el-table-column prop="startTime" label="开始时间" width="160" />
          
          <el-table-column prop="endTime" label="结束时间" width="160" />
          
          <el-table-column prop="department" label="盘点部门" width="120" show-overflow-tooltip />
          
          <el-table-column prop="creatorId" label="制单人ID" width="100" />
          <el-table-column prop="creatorName" label="制单人" width="120" show-overflow-tooltip />
          
          <el-table-column prop="handlerId" label="处理人ID" width="100" />
          <el-table-column prop="handlerName" label="处理人" width="120" show-overflow-tooltip />
          
          <el-table-column prop="outStatus" label="出库状态" width="100" />
          
          <el-table-column prop="inStatus" label="入库状态" width="100" />
          
          <el-table-column prop="remark" label="备注" width="200" show-overflow-tooltip />
          
          <el-table-column prop="createTime" label="制单时间" width="160" />
          
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="text" text-color="#409EFF" @click="handleViewDetail(scope.row)">查看</el-button>
              <el-button type="text" text-color="#F56C6C" @click="deleteItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 明细弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`盘点明细 - ${currentCountCode}`"
      width="80%"
      destroy-on-close
    >
      <el-table
        v-loading="detailLoading"
        :data="detailList"
        stripe
        border
        style="width: 100%"
        height="500px"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productCode" label="商品编码" width="150" show-overflow-tooltip />
        <el-table-column prop="productName" label="商品名称" width="200" show-overflow-tooltip />
        <el-table-column prop="spec" label="规格" width="120" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="countLocation" label="盘点仓位" width="120" show-overflow-tooltip />
        <el-table-column prop="bookStock" label="账面数量" width="100" />
        <el-table-column prop="countQuantity" label="盘点数量" width="100" />
        <el-table-column prop="profitLossQuantity" label="盈亏数量" width="100">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.profitLossQuantity < 0, 'text-success': row.profitLossQuantity > 0 }">
              {{ row.profitLossQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="referencePrice" label="参考单价" width="100" />
        <el-table-column prop="bookAmount" label="账面金额" width="120" />
        <el-table-column prop="profitLossAmount" label="盈亏金额" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.profitLossAmount < 0, 'text-success': row.profitLossAmount > 0 }">
              {{ row.profitLossAmount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="countStatus" label="盘点状态" width="100" />
        <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const typeLoading = ref(false)
const warehouseLoading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const warehouseList = ref([])
const typeList = ref([
  { label: '存货盘点', value: '存货盘点' },
  { label: '期初盘点', value: '期初盘点' },
  { label: '期末盘点', value: '期末盘点' }
])

// 明细弹窗相关数据
const dialogVisible = ref(false)
const detailLoading = ref(false)
const detailList = ref([])
const currentCountCode = ref('')

// 搜索表单
const searchForm = reactive({
  countCode: '',
  countStatus: '',
  countType: '',
  warehouseId: '',
  startTime: '',
  endTime: '',
  creatorId: ''
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格高度计算
const tableHeight = computed(() => {
  return window.innerHeight - 400
})

// 盘点结果类型映射
const getResultType = (result) => {
  const typeMap = {
    '草稿': 'info',
    '有盈亏': 'warning',
    '无盈亏': 'success'
  }
  return typeMap[result] || 'default'
}

// 获取仓库列表
const fetchWarehouseList = async () => {
  warehouseLoading.value = true
  try {
    console.log('正在获取仓库列表...')
    // 使用新的API路径
    const response = await proxy.http.get('/api/Outbound/GetWarehouses/GetWarehouses', {}, false)
    
    // 处理响应数据（根据新的响应格式）
    if (response && response.code === 200) {
      // 根据API返回的数据结构转换为页面需要的格式
      warehouseList.value = (response.data || []).map(warehouse => ({
        warehouseId: warehouse.id, // 使用小写的id
        warehouseName: warehouse.warehouseName // 使用小写的warehouseName
      }))
      console.log('成功获取仓库列表:', warehouseList.value)
    } else {
      console.error('获取仓库列表失败，响应:', response)
      ElMessage.warning(response?.message || '获取仓库列表失败，使用默认数据')
      // 设置默认仓库列表作为备用
      setDefaultWarehouseList()
    }
  } catch (error) {
    console.error('获取仓库列表异常:', error)
    ElMessage.warning('获取仓库列表失败，使用默认数据')
    // 出现异常时使用默认数据
    setDefaultWarehouseList()
  } finally {
    warehouseLoading.value = false
  }
}

// 设置默认仓库列表
const setDefaultWarehouseList = () => {
  warehouseList.value = [
    { warehouseId: 1, warehouseName: '仓库一' },
    { warehouseId: 2, warehouseName: '仓库二' },
    { warehouseId: 3, warehouseName: '仓库三' },
    { warehouseId: 4, warehouseName: '仓库四' },
    { warehouseId: 5, warehouseName: '仓库五' },
    { warehouseId: 6, warehouseName: '仓库八' },
    { warehouseId: 7, warehouseName: '仓库十' }
  ]
  console.log('已使用默认仓库列表:', warehouseList.value)
}


// 页面初始化
onMounted(async () => {
  await Promise.all([
    fetchWarehouseList(), // 调用仓库列表加载
  ])
  fetchData()
})

// 获取盘点单列表
const fetchData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      // 仅添加非空的搜索条件
      ...(searchForm.countCode ? { countCode: searchForm.countCode } : {}),
      ...(searchForm.countType ? { countType: searchForm.countType } : {}),
      ...(searchForm.warehouseId ? { warehouseId: searchForm.warehouseId } : {}),
      ...(searchForm.countStatus ? { countStatus: searchForm.countStatus } : {}),
      ...(searchForm.startTime ? { startTime: searchForm.startTime } : {}),
      ...(searchForm.endTime ? { endTime: searchForm.endTime } : {}),
      ...(searchForm.creatorId ? { creatorId: searchForm.creatorId } : {})
    }

    const response = await proxy.http.get('/api/InventoryCount/GetInventoryCountPageList', params, false)
    if (response && response.status) {
      // 直接使用后端返回的数据，无需额外处理
      tableData.value = response.data?.data || []
      pagination.total = response.data?.totalCount || 0
    } else {
      ElMessage.error(response?.message || '获取盘点单列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取盘点单列表失败:', error)
    ElMessage.error('网络错误，请检查网络连接后重试')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.pageIndex = 1
  fetchData()
}

// 新增盘点
const handleAdd = () => {
  router.push('/InventoryCountItem')
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 获取盘点明细
const fetchCountItems = async (countCode) => {
  detailLoading.value = true
  try {
    const params = { countCode }
    console.log('调用API获取盘点明细，countCode:', countCode)
    const response = await proxy.http.get('/api/InventoryCount/GetCountItems', params, false)
    console.log('API响应:', response)
    // 修改条件判断，使用success字段而不是status字段
    if (response && response.success) {
      detailList.value = response.data || []
      console.log('获取到的明细数据:', detailList.value)
    } else {
      ElMessage.error(response?.message || '获取盘点明细失败')
      detailList.value = []
    }
  } catch (error) {
    console.error('获取盘点明细失败:', error)
    ElMessage.error('网络错误，请检查网络连接后重试')
    detailList.value = []
  } finally {
    detailLoading.value = false
  }
}

// 查看详情
const handleViewDetail = async (row) => {
  currentCountCode.value = row.countCode
  await fetchCountItems(row.countCode)
  dialogVisible.value = true
}

// 编辑
const edit = (row) => {
  router.push(`/inventory-count/edit/${row.inventoryCountId}`)
}

// 删除
const deleteItem = async (row) => {
  ElMessageBox.confirm(
    `确定要删除盘点单【${row.countCode}】吗？删除后不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await proxy.http.delete(`/api/InventoryCount/Delete?id=${row.inventoryCountId}`, false)
      if (response && response.status) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(response?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除盘点单失败:', error)
      ElMessage.error('网络错误，删除失败')
    }
  })
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  fetchData()
}

// 页面初始化
onMounted(async () => {
  await Promise.all([
    fetchWarehouseList(), // 调用仓库列表加载
  ])
  fetchData()
})
</script>

<style scoped>
.inventory-count-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 文本颜色样式 */
.text-danger {
  color: #F56C6C;
}

.text-success {
  color: #67C23A;
}

/* 搜索表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-count-page {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .table-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>